package org.insist.best.codeGenerator.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONObject;
import org.insist.best.codeGenerator.bo.GenerateCodeBo;
import org.insist.best.codeGenerator.bo.QueryBo;
import org.insist.best.codeGenerator.core.DbConfig;
import org.insist.best.codeGenerator.service.GeneratorService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
public class GeneratorController {

    @Resource
    private GeneratorService generatorService;

    @PostMapping(value = "/list")
    @ResponseBody
    public JSONObject list(@RequestBody QueryBo queryBo) {
        DbConfig dbConfig = queryBo.toDbConfig();
        return generatorService.queryList(dbConfig, queryBo.getQueryTableName(), queryBo.getPage(), queryBo.getPageSize());
    }

    @PostMapping(value = "/code")
    public void code(@RequestBody GenerateCodeBo codeBo, HttpServletResponse response) throws IOException {
        if (CollectionUtil.isEmpty(codeBo.getTableNames())) {
            return;
        }
        byte[] data = generatorService.generateCode(codeBo);
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"code.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IoUtil.write(response.getOutputStream(), true, data);
    }
}
